﻿import VTitle from '@/components/common/MainTitle.vue'
// 页面配置的弹窗
import TemplateSettings from '@/components/MetaFormComponents/MetaForm.vue'
// 页面预览的弹窗
import ShowMetaFormLayout from '@/components/MetaFormComponents/ShowMetaFormLayout.vue'
export default {
  data () {
    return {
      titleName: '动态模板管理',
      tableData: [],
      tableColumn: [
        {
          text: '名称',
          indexName: 'name'
        },
        {
          text: '类别',
          indexName: 'category'
        },
        {
          text: '是否锁定',
          indexName: 'is_lock'
        }
      ],
      // 编辑和新增的弹窗部分
      dialogTitle: '',
      dialogFormVisible: false,
      // 表单规则
      ruleForm: {
        uid: '',
        name: '',
        desc: '',
        category: '',
        settings: ''
      },
      labelWidth: '86px',
      operationType: '',
      rules: {
        name: [
          {required: true, message: '模板名称不能为空', trigger: 'blur'}
        ]
      },
      // 页码部分
      searchKey: '',
      // 保留输入的searchKey
      saveSearchKey: '',
      isSearch: false,
      totalData: [],
      filterData: [],
      totalLength: 0,
      currentPage: 1,
      pageSize: 10,
      loading: false,
      // 页面配置的弹窗部分
      propsInfo: {
        settingVisible: false,
        settingFrom: 'templateSetting',
        settings: '',
        name: '',
        uid: '',
        metaUid: null,
        showFixedColumn: ''
      },
      // 页面预览的弹窗
      previewTitle: '',
      previewFormVisible: false,
      previewPageData: null
    }
  },
  created () {
    this.getAllPages()
  },
  methods: {
    // 初始化表格的数据
    getAllPages () {
      // 在检索的值清空前，先保存到变量saveSearchKey中
      this.saveSearchKey = this.searchKey
      this.searchKey = ''
      this.loading = true
      this.$get('/d_template').then((data) => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          this.totalData = dataResult.data
          this.totalLength = dataResult.data.length
          // 调用方法进行页面渲染
          this.showData(this.totalData)
          // 在不是删除可新增时，保留searchkey
          if (this.operationType && this.operationType !== 'add' && this.operationType !== 'delete') {
            this.searchKey = this.saveSearchKey
          }
          this.loading = false
        } else {
          this.$message.error(data.data.result.msg)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 获取指定页面的数据
    getCurrentPageInfo (uid) {
      this.loading = true
      this.$get('/d_template/' + uid).then((data) => {
        let dataResult = data.data.result
        if (dataResult.code === 'success') {
          this.loading = false
          this.ruleForm.name = dataResult.data.name
          this.ruleForm.desc = dataResult.data.desc
          this.ruleForm.category = dataResult.data.category
          this.ruleForm.uid = dataResult.data.uid
          this.ruleForm.settings = dataResult.data.settings
          // 编辑按钮时
          if (this.operationType === 'edit') {
            this.dialogFormVisible = true
          } else if (this.operationType === 'setting') {
            // 配置设定时
            this.$set(this.propsInfo, 'settingFrom', 'templateSetting')
            this.$set(this.propsInfo, 'settings', dataResult.data.settings)
            this.$set(this.propsInfo, 'name', dataResult.data.name)
            this.$set(this.propsInfo, 'uid', dataResult.data.uid)
            this.$set(this.propsInfo, 'metaUid', null)
            this.$set(this.propsInfo, 'settingVisible', true)
          } else if (this.operationType === 'preview') {
            if (dataResult.data.settings) {
              this.previewPageData = JSON.parse(dataResult.data.settings)
              this.previewTitle = this.previewPageData.pageConfig.name + '预览'
              this.previewFormVisible = true
            } else {
              this.$message({
                message: '该动态模板还未进行配置设定，请先进行配置设定再预览',
                type: 'warning'
              })
            }
          }
        } else {
          this.$message.error(data.data.result.msg)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 新建模板时
    handleAdd () {
      this.dialogFormVisible = true
      this.dialogTitle = '添加动态模板基本信息'
      this.ruleForm.name = ''
      this.ruleForm.desc = ''
      this.ruleForm.category = ''
      this.ruleForm.uid = ''
      this.ruleForm.settings = ''
      this.operationType = 'add'
    },
    // 编辑模板的基本信息
    handleEdit (row) {
      if (row.is_lock) {
        this.$message({
          message: '该动态模板已锁定，需先解锁才可进行编辑操作',
          type: 'warning'
        })
      } else {
        this.dialogTitle = '编辑动态模板基本信息'
        this.operationType = 'edit'
        this.getCurrentPageInfo(row.uid)
      }
    },
    // 删除模板
    handleDelete (row) {
      if (row.is_lock) {
        this.$message({
          message: '该动态模板已锁定，需先解锁才可进行删除操作',
          type: 'warning'
        })
        return
      }
      this.$confirm('此操作将永久删除该动态模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonClass: 'el-button--info',
        cancelButtonText: '取消'
      }).then(() => {
        this.operationType = 'delete'
        this.loading = true
        this.$delete('/d_template/' + row.uid).then((data) => {
          this.loading = false
          let dataResult = data.data.result
          if (dataResult.code === 'success') {
            this.$message({
              message: '删除成功',
              type: 'success'
            })
            this.getAllPages()
          } else {
            this.$message.error(data.data.result.msg)
          }
        }).catch((error) => {
          console.log(error)
        })
      }).catch(() => {})
    },
    // 预览模板时
    preview (row) {
      this.operationType = 'preview'
      this.getCurrentPageInfo(row.uid)
    },
    // 解锁或者锁定的操作
    handleLockAndUnlock (row, type) {
      let msg = '确定要为该动态模板解锁么？'
      if (type === 'lock') {
        msg = '确定要锁定该动态模板么？'
      }
      this.$confirm(msg, '提示', {
        confirmButtonText: '确定',
        cancelButtonClass: 'el-button--info',
        cancelButtonText: '取消'
      }).then(() => {
        this.operationType = 'lock'
        this.loading = true
        this.$patch('/d_template/' + row.uid + '/' + type).then((data) => {
          this.loading = false
          let dataResult = data.data.result
          if (dataResult.code === 'success') {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.getAllPages()
          } else {
            this.$message.error(data.data.result.msg)
          }
        }).catch((error) => {
          console.log(error)
        })
      }).catch(() => {})
    },
    // 配置设定
    handleSetting (row) {
      if (row.is_lock) {
        this.$message({
          message: '该动态模板已锁定，需先解锁才可进行配置设定操作',
          type: 'warning'
        })
      } else {
        this.operationType = 'setting'
        this.getCurrentPageInfo(row.uid)
      }
    },
    // 设定成功时
    sureSetting (fromSetting) {
      this.$set(this.ruleForm, 'settings', fromSetting.jsonData)
      this.submitEdit()
    },
    // 取消设定时
    giveUpSetting () {
      this.$set(this.propsInfo, 'settingVisible', false)
    },
    // 提交编辑的方法
    submitEdit () {
      this.loading = true
      this.$patch('/d_template/' + this.ruleForm.uid, {
        name: this.ruleForm.name,
        desc: this.ruleForm.desc,
        settings: this.ruleForm.settings,
        category: this.ruleForm.category
      }).then((data) => {
        this.loading = false
        if (data.data.result.code === 'success') {
          // 当为配置设定时
          if (this.operationType === 'setting') {
            this.$set(this.propsInfo, 'settingVisible', false)
            this.$message({
              message: '配置设定成功',
              type: 'success'
            })
          } else {
            // 编辑普通的信息时
            this.dialogFormVisible = false
            this.$message({
              message: '编辑成功',
              type: 'success'
            })
          }
          this.getAllPages()
        } else {
          this.$message.error(data.data.result.msg)
        }
      })
    },
    // 提交新增的方法
    submitAdd () {
      this.loading = true
      this.$post('/d_template', {
        name: this.ruleForm.name,
        desc: this.ruleForm.desc,
        settings: this.ruleForm.settings,
        category: this.ruleForm.category
      }).then((data) => {
        this.loading = false
        if (data.data.result.code === 'success') {
          this.dialogFormVisible = false
          this.$message({
            message: '添加成功',
            type: 'success'
          })
          this.getAllPages()
        } else {
          this.$message.error(data.data.result.msg)
        }
      }).catch((error) => {
        console.log(error)
      })
    },
    // 点击新增编辑弹窗的确定按钮
    submitForm (forms, submitType) {
      this.$refs[forms].validate((valid) => {
        if (valid) {
          if (submitType === 'edit') {
            this.submitEdit()
          } else if (submitType === 'add') {
            this.submitAdd()
          }
        } else {
          return false
        }
      })
    },
    // 点击弹窗的取消按钮
    resetForm (forms) {
      this.$refs[forms].clearValidate()
      this.dialogFormVisible = false
    },
    closeDialog () {
      this.$refs.ruleForm.clearValidate()
    },
    // 将页码与数据关联
    showData (myData) {
      // 渲染表格的数据存放在 this.tableData 中
      this.tableData = []
      if (myData.length) {
        let from = (this.currentPage - 1) * this.pageSize
        let to = this.currentPage * this.pageSize
        if (to > myData.length) {
          to = myData.length
        }
        for (; from < to; from++) {
          this.tableData.push(myData[from])
        }
      }
    },
    // 底部页码的部分
    handleSizeChange (val) {
      this.pageSize = val
      // 需要判断是否是检索的数据
      if (this.isSearch) {
        this.showData(this.filterData)
      } else {
        this.showData(this.totalData)
      }
    },
    handleCurrentChange (val) {
      this.currentPage = val
      // 需要判断是否是检索的数据
      if (this.isSearch) {
        this.showData(this.filterData)
      } else {
        this.showData(this.totalData)
      }
    }
  },
  watch: {
    // 搜索的功能
    searchKey: {
      handler: function (val, oldVal) {
        // 当检索的内容为空时需要将表格的内容还原
        if (this.$trim(val) === '') {
          this.pageSize = 10
          this.currentPage = 1
          this.totalLength = this.totalData.length
          this.isSearch = false
          // 调用方法进行页面渲染
          this.showData(this.totalData)
        } else {
          // 检索结果的数据存放在 this.filterData 中
          this.filterData = []
          this.totalData.forEach((value, index) => {
            if (value.name) {
              if (value.name.indexOf(this.searchKey) >= 0) {
                this.filterData.push(value)
              }
            }
          })
          this.isSearch = true
          this.currentPage = 1
          this.totalLength = this.filterData.length
          // 调用方法进行页面渲染
          this.showData(this.filterData)
        }
      },
      deep: true
    }
  },
  components: {
    VTitle, TemplateSettings, ShowMetaFormLayout
  }
}
